package com.huang825172.sbog.Tabs.Mine.LoginPage.Store;

import android.content.Context;

import com.google.gson.Gson;
import com.huang825172.sbog.BaseFlux.Action.BaseAction;
import com.huang825172.sbog.BaseFlux.Store.BaseStore;
import com.huang825172.sbog.GlobalManager.LoginStateManager;
import com.huang825172.sbog.R;
import com.huang825172.sbog.Tabs.Mine.LoginPage.Action.LoginAction;
import com.huang825172.sbog.Tabs.Mine.LoginPage.Action.RememberAction;
import com.huang825172.sbog.Tabs.Mine.LoginPage.Store.Datas.Login;
import com.huang825172.sbog.Tabs.Mine.LoginPage.Store.Datas.LoginRes;
import com.huang825172.sbog.Util.StatusCacheUtil;

import java.util.ArrayList;
import java.util.List;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class Store extends BaseStore {
    private boolean LoginStatus = false;
    private boolean LoginRememberStatus = false;
    private String loginResponseRaw;
    private StatusCacheUtil cache;
    private StatusCacheUtil statusCache;
    private String exception;

    public Store(Context context) {
        super(context);
        this.cache = new StatusCacheUtil(context.getResources().getString(R.string.loginPageCache), context);
        this.statusCache = new StatusCacheUtil(context.getResources().getString(R.string.loginStatusCache), context);
        this.LoginRememberStatus = cache.getAsBoolean("LoginPage_RememberStatus");
        this.exception = "";
    }

    //注册希望订阅的Action
    @Override
    public List<String> getActionLabels() {
        ArrayList<String> labels = new ArrayList<>();
        labels.add("LoginPageLoginAction");
        labels.add("LoginPageRememberAction");
        return labels;
    }

    @Override
    public void changeData(BaseAction action) {
        super.changeData(action);
        switch (action.getLabel()) {
            case "LoginPageLoginAction": {
                LoginAction act = (LoginAction) action;
                this.Login(act.getUsername(), act.getPassword());
                if (getLoginRememberStatus()) {
                    cache.put("LoginPage_RememberUsername", act.getUsername());
                    cache.put("LoginPage_RememberPassword", act.getPassword());
                }
                break;
            }
            case "LoginPageRememberAction": {
                RememberAction act = (RememberAction) action;
                this.changeRememberStatus(act.getUsername(), act.getPassword());
                this.notifyDataChanged(action.getLabel());
                break;
            }
            default:
                break;
        }
    }

    // 处理登录请求的异步函数
    private void Login(final String username, String password) {
        LoginStatus = false;
        Login info = new Login(username, password);
        final Gson gson = new Gson();
        String infoStr = gson.toJson(info);
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(context.getResources().getString(R.string.server_baseUrl))
                .build();
        Interfaces request = retrofit.create(Interfaces.class);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), infoStr);
        Call<ResponseBody> call = request.Login(body);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    loginResponseRaw = response.body().string();
                    LoginRes resObj = gson.fromJson(loginResponseRaw, LoginRes.class);
                    if (resObj.code == 200) {
                        LoginStatus = true;
                        statusCache.put("token", resObj.data.token);
                        statusCache.put("loginPhone", username);//暂时没有做用户名登录的支持
                    }
                } catch (Exception e) {
                    loginResponseRaw = null;
                    LoginStatus = false;
                    exception = e.getStackTrace().toString();
                    e.printStackTrace();
                }
                notifyDataChanged("LoginPageLoginAction");
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                loginResponseRaw = null;
                LoginStatus = false;
                exception = t.getStackTrace().toString();
                t.printStackTrace();
                notifyDataChanged("LoginPageLoginAction");
            }
        });
    }

    //当记住密码选项变更的时候
    private void changeRememberStatus(String username, String password) {
        this.LoginRememberStatus = !this.LoginRememberStatus;
        if (this.LoginRememberStatus) {
            cache.put("LoginPage_RememberUsername", username);
            cache.put("LoginPage_RememberPassword", password);
            cache.put("LoginPage_RememberStatus", true);
        } else {
            cache.remove("LoginPage_RememberUsername");
            cache.remove("LoginPage_RememberPassword");
            cache.put("LoginPage_RememberStatus", false);
        }
        notifyDataChanged("LoginPageRememberAction");
    }

    public boolean getLoginStatus() {
        return LoginStatus;
    }

    public String getLoginResponseRaw() {
        return loginResponseRaw;
    }

    public boolean getLoginRememberStatus() {
        return LoginRememberStatus;
    }

    public String getRememberUsername() {
        return cache.getAsString("LoginPage_RememberUsername");
    }

    public String getRememberPassword() {
        return cache.getAsString("LoginPage_RememberPassword");
    }

    public String getExceptionString() {
        return exception;
    }
}
